package mx.com.sinformex.simbel.pages;

import mx.com.sinformex.simbel.db.dao.IAdminDataAccess;
import mx.com.sinformex.simbel.db.eos.User;
import mx.com.sinformex.simbel.utils.Session;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tapestry5.annotations.ApplicationState;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;

/**
 * Start page of application simbel.
 */
public class Index {
	
	@Property
	private String username;
	@Property
	private String password;
	@Inject
	private IAdminDataAccess dao;
	
	@InjectPage
	private Wellcome page;
	@ApplicationState 
	private Session session;
	@Property
	@Persist
	private String error ;
	
	private final Log log = LogFactory.getLog(getClass());
	
	public Object onValidateForm() {
		User user = dao.getUser(username, password);
		if(user == null) {
			log.error(String.format("Invalid user %s", username));
			error = String.format("Invalid user %s or invalid password.", username);
			return null;
		}
		session.setUser(user);
		return page;
	}
	
	public boolean getHasError() {
		return error != null;
	}

}
